[Coding011] LeetCode 2

Add Two Numbers

Ben 2023/08/02

More coding records

Get the knowledge flowing and circulating! :)

目录

题目: 2. Add Two Numbers

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example 1:

img

Example 2:

Example 3:

Constraints:

代码1

代码2

复杂度分析

有两个链表,复杂度应该是:O(max(n,m))

知识点积累 (Java)

  1. dummy伪结点的使用,更熟悉了一点;

    • 先新建dummy结点;

    • 然后用一个指针p指向dummy

    • 然后只操作这个指针pdummy不动,这样的话,最后只需要返回dummy即可!

  2. 两数之和要有进位位,进位位的经典计算方法

    carry = sum / 10;

    sum = sum - carry * 10;

  3. 单链表类的使用

    • 新建一个结点:ListNode temp = new ListNode(val);

    • 链接一个结点:p.next = temp;

  4. 条件表达式的使用